package com.littlepay.kr4.paulin.dfeba77.utils;

import android.app.Activity;
import android.content.Context;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.littlepay.kr4.paulin.dfeba77.R;

/**
 * Created by 77dfeba on 2017/4/28.
 * build Inner_keyboard that can launch more quickly
 */

public class KeyboardUtil {

    private Context ctx;
    private Activity act;
    private KeyboardView keyboardView;
    //private Keyboard k1;// 字母键盘
    private Keyboard k2;// 数字键盘
    //public boolean isnun = false;// 是否数据键盘
    //public boolean isupper = false;// 是否大写

    private EditText ed;

    public KeyboardUtil(Activity act, Context ctx, EditText edit) {
        this.act = act;
        this.ctx = ctx;
        this.ed = edit;
        //k1 = new Keyboard(ctx, R.xml.qwerty);
        k2 = new Keyboard(ctx, R.xml.symbols);
        keyboardView = (KeyboardView) act.findViewById(R.id.keyboard_view);
        keyboardView.setKeyboard(k2);
        keyboardView.setEnabled(true);
        keyboardView.setPreviewEnabled(false);//不显示按下预览
        keyboardView.setOnKeyboardActionListener(listener);
        //给edittext监听最多两位小数点
        setPricePoint(ed);
        //judgeNumber(ed.getText());
    }

    private KeyboardView.OnKeyboardActionListener listener = new KeyboardView.OnKeyboardActionListener() {
        @Override
        public void swipeUp() {
        }

        @Override
        public void swipeRight() {
        }

        @Override
        public void swipeLeft() {
        }

        @Override
        public void swipeDown() {
        }

        @Override
        public void onText(CharSequence text) {
        }

        @Override
        public void onRelease(int primaryCode) {
        }

        @Override
        public void onPress(int primaryCode) {

        }

        @Override
        public void onKey(int primaryCode, int[] keyCodes) {
            Editable editable = ed.getText();
            int start = ed.getSelectionStart();
            if (primaryCode == Keyboard.KEYCODE_CANCEL) {// 完成
                hideKeyboard();
            } else if (primaryCode == Keyboard.KEYCODE_DELETE) {// 回退
                if (editable != null && editable.length() > 0) {
                    if (start > 0) {
                        editable.delete(start - 1, start);
                    }
                }
            }else if(primaryCode == 46){
                EditText editText = (EditText) act.findViewById(R.id.cost_input);
                if (editText.getText().toString().length() == 0){
                    //输入点的时候变成0.
                    editable.insert(start, Character.toString((char) 48));
                    editable.insert(start+1, Character.toString((char) primaryCode));
                }else if(!editText.getText().toString().contains(".")){
                    //输入点的时候
                    editable.insert(start, Character.toString((char) primaryCode));
                }
            }
            else {
                editable.insert(start, Character.toString((char) primaryCode));
            }
        }
    };



    public void showKeyboard() {
        int visibility = keyboardView.getVisibility();
        if (visibility == View.GONE || visibility == View.INVISIBLE) {
            keyboardView.setVisibility(View.VISIBLE);
        }
    }

    public void hideKeyboard() {
        int visibility = keyboardView.getVisibility();
        if (visibility == View.VISIBLE) {
            keyboardView.setVisibility(View.INVISIBLE);
        }
    }
    /*由小源提供：
      * 使用时需设置ED为decimal
      * 改进可以使用正则表达式
      * @param editText 被控制的ED*/
    private void setPricePoint(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s,
                                      int start,
                                      int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    //1 2最多是一位小数，2 3是最多两位
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                        Toast.makeText(ctx,"消费最多输入两位小数",Toast.LENGTH_SHORT).show();
                    }
                }else {

                    if (s.toString().length() <= 7) {
                        return;//小于7位数直接返回
                    } else {
                        editText.getText().delete(7, 8);//大于五位数就删掉第六位（只会保留五位） 5 ,6
                        Toast.makeText(ctx,"整数部分最多7位",Toast.LENGTH_SHORT).show();
                        return;
                    }

                }
                if (s.toString().trim().equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                    //Toast.makeText(ctx,"最多输入两位小数",Toast.LENGTH_SHORT).show();
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        //Toast.makeText(ctx,"最多输入两位小数",Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s,
                                          int start,
                                          int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });

    }
    public void judgeNumber(Editable edt){

        String temp = edt.toString();
        int posDot = temp.indexOf(".");//返回指定字符在此字符串中第一次出现处的索引
        if (posDot <= 0) {//不包含小数点
            if (temp.length() <= 7) {
                return;//小于7位数直接返回
            } else {
                edt.delete(7, 8);//大于五位数就删掉第六位（只会保留五位） 5 ,6
                return;
            }
        }
        if (temp.length() - posDot - 1 > 2)//如果包含小数点
        {
            edt.delete(posDot + 3, posDot + 4);//删除小数点后的第三位
        }
    }
/*  private boolean isword(String str){
        String wordstr = "abcdefghijklmnopqrstuvwxyz";
        if (wordstr.indexOf(str.toLowerCase())>-1) {
            return true;
        }
        return false;
    }*/

}
